<?php
/**
 * File Name: Qrcode.php
 */

namespace App\Services\Wechat;

use App\Models\WechatSet;
use App\Support\Wechat\QRCode as QR;
use App\Support\Wechat\Media;
use App\Support\MemcacheSASL;
use Image;
class Qrcode
{
    public function __construct(Member $member, WechatSet $wechatSet)
    {
        $this->member = $member;
        $this->memcache = new MemcacheSASL;
        $this->memcache->addServer(env('MEMCACHE_HOST', '127.0.0.1'), env('MEMCACHE_PORT', '11211'));
        $this->wechat = $wechatSet->getWechatSet();
    }

    public function getMedia($message)
    {
        $openid = $message->FromUserName;
        $key = 'yun_qrcode_'.$openid;
        $qrcode = $this->memcache->get($key);
        if($qrcode)
        {
            //获取缓存
            $endtime = time() > ($qrcode['qrcodetime'] + 259000);
            if($endtime){
                //过期则执行
                goto media;
            }
            //return Redis::hget($key, 'qrcode');
            return $qrcode['qrcode'];
        }
        //过期则执行
        media:
        //上传二维码并返回媒体ID
        $wechat = $this->wechat;
        $path = $this->getQrcode($openid);
        $media = new Media($wechat['app_id'], $wechat['app_secret']);
        //合并生成图片，返回图片路径
        $media = $media->image($path);
        if($media)
        {
            $data = ['yun_qrcode_'=>$media['media_id'], 'qrcodetime'=>time()];
            $this->memcache->set($key, $data);
        }
        return $media['media_id'];
    }

    public function getQrcode($openid)  {

        $is_m = $this->memcache->get('yun_openid_'.$openid);
        if($is_m){
            $mid = $is_m['id'];
        }else{
            $member = $this->member->addMember($openid); //会员信息入库
            $mid = $member['id'];
        }
        $appid = $this->wechat['app_id'];
        $appsecret = $this->wechat['app_secret'];
        $qrcode = new QR($appid, $appsecret);
        $result = $qrcode->temporary($mid, 86400*30);
        //info($result);
        $ticket = $result->ticket;


        //设置二维码路径
        $number = $mid%100;
        $path = 'downloads/qrcode/'.$number.'/'.$openid.'.jpg';
        //$path2 = 'downloads/qrcode/'.$number.'/'.$openid.'2.jpg';
        if(!file_exists($path) || time() > ($this->memcache->get('qrimgtime') + 86400*29))//当图片不存在或图片时间超过29天时
        {
            //下载二维码
            $dir = 'downloads/qrcode/'.$number;
            if(!is_dir($dir))
            {
                mkdir($dir, 0755);
            }
            $qrcode->download($ticket, $path);
            $this->memcache->set('qrimgtime', time());
        }

        return $path;
    }
}